package com.lyf.design.learn.effectivejava.object.serviceprovider;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author LYF
 * @date 2022/6/28
 */
public class Services {
    private Services(){}

    /*final关键字的理解与使用*/
    private final static ConcurrentHashMap<String,ServiceProvider> serviceProviders
            = new ConcurrentHashMap<>();

    private final static String DEFAULT_NAME = "DEFAULT";

    public static boolean registerProvider(String providerName,ServiceProvider serviceProvider){
        if(!serviceProviders.containsKey(providerName)){
            serviceProviders.put(providerName,serviceProvider);
        }
        return true;
    }

    public static boolean registerDefaultProvider(ServiceProvider serviceProvider){
        serviceProviders.put(DEFAULT_NAME,serviceProvider);
        return true;
    }

    static Service defaultServiceInstance() throws Exception {
           return serviceInstance(DEFAULT_NAME);
    }

    static Service serviceInstance(String serviceName) throws Exception {
        ServiceProvider serviceProvider=serviceProviders.get(serviceName);
        if(serviceProvider==null){
            throw new Exception("No Provider...");
            //serviceProvider = new DefaultServiceProvider();
        }
        return serviceProvider.newService();
    }

}
